package com.joplus.housekeeper.utils;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;
import android.widget.TextView;

import com.joplus.housekeeper.R;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sc on 2015/10/30.
 */
public class StringUtils {


    private StringUtils() {
        throw new AssertionError();
    }

    /**
     * is null or its length is 0 or it is made by space
     * <p/>
     * <pre>
     * isBlank(null) = true;
     * isBlank(&quot;&quot;) = true;
     * isBlank(&quot;  &quot;) = true;
     * isBlank(&quot;a&quot;) = false;
     * isBlank(&quot;a &quot;) = false;
     * isBlank(&quot; a&quot;) = false;
     * isBlank(&quot;a b&quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0 or it is made by space, return true, else return false.
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * is null or its length is 0
     * <p/>
     * <pre>
     * isEmpty(null) = true;
     * isEmpty(&quot;&quot;) = true;
     * isEmpty(&quot;  &quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0, return true, else return false.
     */
    public static boolean isEmpty(CharSequence str) {
        return (str == null || str.length() == 0 || str == " " || str.toString().trim().isEmpty());
    }


    /**
     * get length of CharSequence
     * <p/>
     * <pre>
     * length(null) = 0;
     * length(\"\") = 0;
     * length(\"abc\") = 3;
     * </pre>
     *
     * @param str
     * @return if str is null or empty, return 0, else return {@link CharSequence#length()}.
     */
    public static int length(CharSequence str) {
        return str == null ? 0 : str.length();
    }

    /**
     * null Object to empty string
     * <p/>
     * <pre>
     * nullStrToEmpty(null) = &quot;&quot;;
     * nullStrToEmpty(&quot;&quot;) = &quot;&quot;;
     * nullStrToEmpty(&quot;aa&quot;) = &quot;aa&quot;;
     * </pre>
     *
     * @param str
     * @return
     */
    public static String nullStrToEmpty(Object str) {
        return (str == null ? "" : (str instanceof String ? (String) str : str.toString()));
    }

    /**
     * capitalize first letter
     * <p/>
     * <pre>
     * capitalizeFirstLetter(null)     =   null;
     * capitalizeFirstLetter("")       =   "";
     * capitalizeFirstLetter("2ab")    =   "2ab"
     * capitalizeFirstLetter("a")      =   "A"
     * capitalizeFirstLetter("ab")     =   "Ab"
     * capitalizeFirstLetter("Abc")    =   "Abc"
     * </pre>
     *
     * @param str
     * @return
     */
    public static String capitalizeFirstLetter(String str) {
        if (isEmpty(str)) {
            return str;
        }

        char c = str.charAt(0);
        return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length())
                .append(Character.toUpperCase(c)).append(str.substring(1)).toString();
    }

    /**
     * encoded in utf-8
     * <p/>
     * <pre>
     * utf8Encode(null)        =   null
     * utf8Encode("")          =   "";
     * utf8Encode("aa")        =   "aa";
     * utf8Encode("啊啊啊啊")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
     * </pre>
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException if an error occurs
     */
    public static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }

    /**
     * encoded in utf-8, if exception, return defultReturn
     *
     * @param str
     * @param defultReturn
     * @return
     */
    public static String utf8Encode(String str, String defultReturn) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return defultReturn;
            }
        }
        return str;
    }

    /**
     * get innerHtml from href
     * <p/>
     * <pre>
     * getHrefInnerHtml(null)                                  = ""
     * getHrefInnerHtml("")                                    = ""
     * getHrefInnerHtml("mp3")                                 = "mp3";
     * getHrefInnerHtml("&lt;a innerHtml&lt;/a&gt;")                    = "&lt;a innerHtml&lt;/a&gt;";
     * getHrefInnerHtml("&lt;a&gt;innerHtml&lt;/a&gt;")                    = "innerHtml";
     * getHrefInnerHtml("&lt;a&lt;a&gt;innerHtml&lt;/a&gt;")                    = "innerHtml";
     * getHrefInnerHtml("&lt;a href="baidu.com"&gt;innerHtml&lt;/a&gt;")               = "innerHtml";
     * getHrefInnerHtml("&lt;a href="baidu.com" title="baidu"&gt;innerHtml&lt;/a&gt;") = "innerHtml";
     * getHrefInnerHtml("   &lt;a&gt;innerHtml&lt;/a&gt;  ")                           = "innerHtml";
     * getHrefInnerHtml("&lt;a&gt;innerHtml&lt;/a&gt;&lt;/a&gt;")                      = "innerHtml";
     * getHrefInnerHtml("jack&lt;a&gt;innerHtml&lt;/a&gt;&lt;/a&gt;")                  = "innerHtml";
     * getHrefInnerHtml("&lt;a&gt;innerHtml1&lt;/a&gt;&lt;a&gt;innerHtml2&lt;/a&gt;")        = "innerHtml2";
     * </pre>
     *
     * @param href
     * @return <ul>
     * <li>if href is null, return ""</li>
     * <li>if not match regx, return source</li>
     * <li>return the last string that match regx</li>
     * </ul>
     */
    public static String getHrefInnerHtml(String href) {
        if (isEmpty(href)) {
            return "";
        }

        String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
        Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
        Matcher hrefMatcher = hrefPattern.matcher(href);
        if (hrefMatcher.matches()) {
            return hrefMatcher.group(1);
        }
        return href;
    }

    /**
     * process special char in html
     * <p/>
     * <pre>
     * htmlEscapeCharsToString(null) = null;
     * htmlEscapeCharsToString("") = "";
     * htmlEscapeCharsToString("mp3") = "mp3";
     * htmlEscapeCharsToString("mp3&lt;") = "mp3<";
     * htmlEscapeCharsToString("mp3&gt;") = "mp3\>";
     * htmlEscapeCharsToString("mp3&amp;mp4") = "mp3&mp4";
     * htmlEscapeCharsToString("mp3&quot;mp4") = "mp3\"mp4";
     * htmlEscapeCharsToString("mp3&lt;&gt;&amp;&quot;mp4") = "mp3\<\>&\"mp4";
     * </pre>
     *
     * @param source
     * @return
     */
    public static String htmlEscapeCharsToString(String source) {
        return StringUtils.isEmpty(source) ? source : source.replaceAll("&lt;", "<").replaceAll("&gt;", ">")
                .replaceAll("&amp;", "&").replaceAll("&quot;", "\"");
    }

    /**
     * transform half width char to full width char
     * <p/>
     * <pre>
     * fullWidthToHalfWidth(null) = null;
     * fullWidthToHalfWidth("") = "";
     * fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
     * fullWidthToHalfWidth("！＂＃＄％＆) = "!\"#$%&";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String fullWidthToHalfWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == 12288) {
                source[i] = ' ';
                // } else if (source[i] == 12290) {
                // source[i] = '.';
            } else if (source[i] >= 65281 && source[i] <= 65374) {
                source[i] = (char) (source[i] - 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * transform full width char to half width char
     * <p/>
     * <pre>
     * halfWidthToFullWidth(null) = null;
     * halfWidthToFullWidth("") = "";
     * halfWidthToFullWidth(" ") = new String(new char[] {12288});
     * halfWidthToFullWidth("!\"#$%&) = "！＂＃＄％＆";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String halfWidthToFullWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == ' ') {
                source[i] = (char) 12288;
                // } else if (source[i] == '.') {
                // source[i] = (char)12290;
            } else if (source[i] >= 33 && source[i] <= 126) {
                source[i] = (char) (source[i] + 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * 给指定TextView 中存在的指定文字设置颜色
     *
     * @param context
     * @param textView
     * @param oldStr   全部文字
     * @param newStr   指定文字
     */
    public static void setAppointTextColor(Context context, TextView textView, String oldStr, String newStr) {

        if (isEmpty(oldStr) || isEmpty(newStr)) {
            return;
        }


        int index = oldStr.indexOf(newStr);
        if (index != -1 && index < oldStr.length()) {

            try {
                SpannableStringBuilder builder = new SpannableStringBuilder(oldStr);

                builder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.colorAccent))
                        , index, index + newStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.setText(builder);
            } catch (Exception e) {
                textView.setText(oldStr);
            }
        } else {
            textView.setText(oldStr);
        }
    }


    /**
     * 设置textView文字
     *
     * @param textView
     * @param text
     */
    public static void setText(TextView textView, String text) {
        if (textView == null)
            return;
        if (!isEmpty(text)) {
            textView.setText(text);
        } else {
            textView.setText("");

        }
    }

    /**
     * 设置textView文字
     *
     * @param textView
     * @param text
     */
    public static void setText4Color(TextView textView, String text, int color, int start, int end) {
        if (textView == null && end > text.length())
            return;
        if (!isEmpty(text)) {
            SpannableString spannableString = new SpannableString(text);
            spannableString.setSpan(new ForegroundColorSpan(color), start, end,
                    SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            textView.setText(spannableString);
        } else {
            textView.setText("");
        }
    }

    public static void setTextLine(TextView textView, String text) {
        if (textView == null)
            return;
        if (!isEmpty(text)) {
            L.e("test" + text);
            textView.setText(text);
            textView.setTextColor(Color.rgb(153, 153, 153));
            textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            textView.setText("");

        }
    }

    public static void setTextMoneyLine(TextView textView, Spannable text) {
        if (textView == null)
            return;
        if (!isEmpty(text)) {
            L.e("test" + text);
            textView.setText(text);
            textView.setTextColor(Color.rgb(153, 153, 153));
            textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            textView.setText("");

        }
    }


    public static void setText(EditText editText, String text) {
        if (editText == null)
            return;
        if (!isEmpty(text)) {
            editText.setText(text);
        } else {
            editText.setText("");

        }
    }


    /**
     * 判断是否是正确手机号
     * 为了全球手机号所以不需要验证了...2017/5/9
     * author Administrator
     * time 2016/7/1 15:47
     */
    public static boolean isMobileNO(String mobiles) {


      /*  Pattern p = Pattern.compile("^((1[3,5,8][0-9])|(14[5,7])|(17[0-9]))\\d{8}$");

        Matcher m = p.matcher(mobiles);

        return m.matches();*/
        return true;

    }


    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String getRandomNumString(int length) {
        String str = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(10);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static void setMoney(TextView tv, String money) {
        if (tv == null) {
            return;
        }
        if (isEmpty(money)) {
            tv.setText(" ");
            return;
        }
        String paidMoneyString = DecimalFormatTool.getPaidMoneyString(money);
        SpannableString spannable = new SpannableString("￥" + paidMoneyString);
        spannable.setSpan(new AbsoluteSizeSpan(12, true), 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannable);
    }

    public static SpannableString getMoney(String money) {
        if (StringUtils.isEmpty(money)) {
            return null;
        }
        String paidMoneyString = DecimalFormatTool.getPaidMoneyString(money);
        SpannableString spannable = new SpannableString("￥" + paidMoneyString);
        spannable.setSpan(new AbsoluteSizeSpan(12, true), 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannable;
    }


    /**
     * 设置textView文字
     *
     * @param textView
     * @param money
     */
    public static void setTextMoney(Context context, TextView textView, String money, String rest) {
        if (textView == null)
            return;
        if (!isEmpty(money) && !isEmpty(rest)) {
            SpannableString spannableString = new SpannableString(rest + ": ￥" + DecimalFormatTool.getPaidMoneyString(money));
            spannableString.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.jo_text_red)), rest.length() + 2, spannableString.length(),
                    SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new AbsoluteSizeSpan(12, true), rest.length() + 2, rest.length() + 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            textView.setText(spannableString);
        } else {
            textView.setText("");
        }
    }

    public static String getRandomUserId() {
        String s = getRandomNumString(13) + getRandomString(4);
        return s;
    }

    public static void setPointsMoney(Context context, TextView tv, String price, String inventory) {
        StringBuffer stringBuffer = new StringBuffer("");
        if (tv == null) {
            return;
        }
        if ((!StringUtils.isEmpty(price) && !"0".equals(price) && !"0.00".equals(price)) && (!StringUtils.isEmpty(inventory) && !"0".equals(inventory) && !"0.00".equals(inventory))) {
            stringBuffer.append(inventory + context.getString(R.string.points) + "+" + DecimalFormatTool.getPaidMoneyString(price) + context.getString(R.string.rmb));
        } else if (!StringUtils.isEmpty(price) && !"0".equals(price) && !"0.00".equals(price)) {
            stringBuffer.append(DecimalFormatTool.getPaidMoneyString(price) + context.getString(R.string.rmb));
        } else if (!StringUtils.isEmpty(inventory) && !"0".equals(inventory) && !"0.00".equals(inventory)) {
            stringBuffer.append(inventory + context.getString(R.string.points));
        } else {
            stringBuffer.append("已失效");
        }

        tv.setText(stringBuffer);
    }

    public static StringBuffer setPointsMoney(Context context, String price, String inventory) {
        StringBuffer stringBuffer = new StringBuffer("");
        if ((!StringUtils.isEmpty(price) && !"0".equals(price) && !"0.00".equals(price)) && (!StringUtils.isEmpty(inventory) && !"0".equals(inventory) && !"0.00".equals(inventory))) {
            stringBuffer.append(inventory + context.getString(R.string.points) + "+" + DecimalFormatTool.getPaidMoneyString(price) + context.getString(R.string.rmb));
        } else if (!StringUtils.isEmpty(price) && !"0".equals(price) && !"0.00".equals(price)) {
            stringBuffer.append(DecimalFormatTool.getPaidMoneyString(price) + context.getString(R.string.rmb));
        } else if (!StringUtils.isEmpty(inventory) && !"0".equals(inventory) && !"0.00".equals(inventory)) {
            stringBuffer.append(inventory + context.getString(R.string.points));
        } else {
            stringBuffer.append("已失效");
        }
        return stringBuffer;
    }
}
